package com.lw.sbdemo2.service;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import com.github.pagehelper.PageHelper;
import com.lw.sbdemo2.common.base.CrudService;
import com.lw.sbdemo2.common.constant.TkConstants;
import com.lw.sbdemo2.common.utils.*;
import com.lw.sbdemo2.common.vo.PageInfo;
import com.lw.sbdemo2.entity.TkExamProductDetail;
import com.lw.sbdemo2.entity.TkExamProductMaster;
import com.lw.sbdemo2.entity.TkUserAnswerExamRecord;
import com.lw.sbdemo2.entity.TkUserErrorExamDetail;
import com.lw.sbdemo2.entity.TkUserInfo;
import com.lw.sbdemo2.mapper.TkExamProductMasterMapper;
import com.lw.sbdemo2.mapper.TkUserAnswerExamRecordMapper;
import com.lw.sbdemo2.mapper.TkUserInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * <p>标题: 用户试卷记录表服务 - 业务逻辑层</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2019</p>
 * <p>公司: 山人行工作室</p>
 *
 * @version: 1.0
 * @author: LinWang
 * @date 2019-4-14
 */
@Slf4j
@Service
public class TkUserAnswerExamRecordService extends CrudService<TkUserAnswerExamRecord, TkUserAnswerExamRecordMapper> {

    @Autowired
    private TkExamProductMasterMapper tkExamProductMasterMapper;

    @Autowired
    private TkUserInfoMapper tkUserInfoMapper;

	/**
     * 获取用户分页列表
     *
     * @param query    搜索关键词
     * @param pageInfo 分页实体
	 * @param tkUserAnswerExamRecord 实体入参
     * @return 用户列表
     */
    public PageInfo<TkUserAnswerExamRecord> findListPage(String query, PageInfo pageInfo, TkUserAnswerExamRecord tkUserAnswerExamRecord) {
        PageHelper.startPage(pageInfo);
        List<TkUserAnswerExamRecord> tkUserAnswerExamRecordlist = this.dao.findListPage(query, tkUserAnswerExamRecord);
        return new PageInfo<>(tkUserAnswerExamRecordlist);
    }

    /**
     * 获取用户答题排名
     *
     * @param tkUserAnswerExamRecord 实体入参
     * @return 用户列表
     */
    public List<TkUserAnswerExamRecord> getRankList(TkUserAnswerExamRecord tkUserAnswerExamRecord) {

        List<TkUserAnswerExamRecord> resultArr = new ArrayList<>();
        List<TkUserAnswerExamRecord> resultNew;
        String examType = tkUserAnswerExamRecord.getExamType();

        if (Objects.equals(examType , TkConstants.EXAM_TYPE_STUDY)) {
            resultNew = this.dao.getRankRateList(tkUserAnswerExamRecord);
            resultArr = CollectionUtils.isEmpty(resultNew) ? null: resultNew.stream().map(item ->{
                String useTime = item.getFirstUseTime();
                String temp = "";
                if (ValidUtil.isNotEmptyAndNull(useTime)) {
                    temp = DateUtils.secToTime(Integer.parseInt(useTime));
                }
                if (ValidUtil.isNotEmptyAndNull(useTime)) {

                }
                item.setFirstUseTime(temp);
                return item;
            }).collect(Collectors.toList());
        } else if (Objects.equals(examType , TkConstants.EXAM_TYPE_MOCK))  {
            resultArr = this.dao.getRankList(tkUserAnswerExamRecord);
        }

        return resultArr;
    }

    /**
     * 获取老师班级下用户答题排名
     *
     * @param tkUserAnswerExamRecord 实体入参
     * @return 用户列表
     */
    public List<TkUserAnswerExamRecord> getTeacherRank(TkUserAnswerExamRecord tkUserAnswerExamRecord) {

        String examType = tkUserAnswerExamRecord.getExamType();
        List<TkUserAnswerExamRecord> resultArr = new ArrayList<>();
        List<TkUserAnswerExamRecord> resultNew;
        if (Objects.equals(examType , TkConstants.EXAM_TYPE_STUDY)) {
            resultNew = this.dao.getTeacherRateRank(tkUserAnswerExamRecord);
            resultArr = CollectionUtils.isEmpty(resultNew) ? null: resultNew.stream().map(item ->{
                String useTime = item.getFirstUseTime();
                String temp = "";
                if (ValidUtil.isNotEmptyAndNull(useTime)) {
                    temp = DateUtils.secToTime(Integer.parseInt(useTime));
                }
                item.setFirstUseTime(temp);
                item.setExamType(TkConstants.EXAM_TYPE_STUDY);
                return item;
            }).collect(Collectors.toList());
        } else if (Objects.equals(examType , TkConstants.EXAM_TYPE_MOCK))  {
            resultNew = this.dao.getTeacherRank(tkUserAnswerExamRecord);
            resultArr = CollectionUtils.isEmpty(resultNew) ? null: resultNew.stream().map(item ->{
                item.setExamType(TkConstants.EXAM_TYPE_MOCK);
                return item;
            }).collect(Collectors.toList());
        }

        return resultArr;
    }

    /**
     * 获取老师班级下用户答题排名
     *
     * @param tkUserAnswerExamRecord 实体入参
     * @return 用户列表
     */
    public List<TkUserAnswerExamRecord> getGradeRank(TkUserAnswerExamRecord tkUserAnswerExamRecord) {

        List<TkUserAnswerExamRecord> resultArr = this.dao.getGradeRank(tkUserAnswerExamRecord);
        return resultArr;
    }

    /**
     * 导出选中的学生答题成绩
     *
     * @param tkUserAnswerExamRecord 实体入参
     * @return 用户列表
     */
    public String exportUserAnswer(TkUserAnswerExamRecord tkUserAnswerExamRecord, HttpServletResponse response) throws Exception {
        String fileName = DateUtils.toShortStringFormat(new Date()) +"学生答题记录";

        //拼接选择试题id
        List<String> examArr;
        List<Map<String , Object>> resultArr = new ArrayList<>();
        String[] examIdArr = tkUserAnswerExamRecord.getExamIdArr().split(",");
        examArr = Arrays.asList(examIdArr);
        //获取选择试题的名称数组
        List<TkExamProductMaster> tkExamProductArr = tkExamProductMasterMapper.selectMaster(examArr);

        //查看班级下的学生
        TkUserInfo tkUserInfo = TkUserInfo.builder().teacherId(tkUserAnswerExamRecord.getTeacherId()).classId(tkUserAnswerExamRecord.getClassId()).build();
        List<TkUserInfo> classStudent = tkUserInfoMapper.findClassStudent(tkUserInfo);

        //获取班级下学习的答题记录
        List<TkUserAnswerExamRecord> tkUserAnswerExamRecords = this.dao.exportUserAnswer(examArr, tkUserAnswerExamRecord);
        Map<String , List<TkUserAnswerExamRecord>> studentExam =
            tkUserAnswerExamRecords.stream().collect(Collectors.groupingBy(TkUserAnswerExamRecord::getUserName));

        //循环判断班级下的学生是否全部答题,初始化学生答题数据
        Map<String , List<TkUserAnswerExamRecord>> examInit = new HashMap<>();
        List<TkUserAnswerExamRecord> initUserExam = new ArrayList<>();
        tkExamProductArr.forEach(item ->{
            TkUserAnswerExamRecord temp = new TkUserAnswerExamRecord();
            temp.setExamId(item.getExamId());
            initUserExam.add(temp);
        });
        classStudent.forEach(item ->{
            String userName = item.getUserName();
            try {
                examInit.put(userName, ListUtils.deepCopy(initUserExam));
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        });

        if (!CollectionUtils.isEmpty(studentExam)) {
            for (Map.Entry<String, List<TkUserAnswerExamRecord>> m : examInit.entrySet()) {
                Map<String , Object> result = new HashMap<>(100);
                String userName = m.getKey();
                List<TkUserAnswerExamRecord> userExamInit = m.getValue();
                List<TkUserAnswerExamRecord> userExam = ValidUtil.isEmptyAndNull(studentExam.get(userName)) ?
                    new ArrayList<>():studentExam.get(userName);
                //赋值学生答题成绩
                userExamInit.forEach(item ->{
                    String examId = item.getExamId();
                    userExam.forEach(temp ->{
                        String examId1 = temp.getExamId();
                        if (Objects.equals(examId , examId1)) {
                            item.setFirstExactRate(temp.getFirstExactRate());
                            item.setFirstAnswerScore(temp.getFirstAnswerScore());
                        }
                    });
                });
                result.put("userName", userName);
                userExamInit.forEach(item -> {
                    //对于小于50分的学生做判断
                    String resultStr = "";
                    BigDecimal resultScore =  ValidUtil.isEmptyAndNull(item.getFirstExactRate()) ? item.getFirstAnswerScore() : item.getFirstExactRate();
                    if (!ValidUtil.isEmptyAndNull(resultScore)) {
                        if (resultScore.compareTo(BigDecimal.valueOf(51)) == -1) {
                            resultStr = String.valueOf(resultScore) + "（还需努力）";
                        } else {
                            resultStr = String.valueOf(resultScore);
                        }
                    } else {
                        resultStr = "无";
                    }
                    result.put(item.getExamId() ,resultStr);

                });
                resultArr.add(result);
            }
        } else {
            for (Map.Entry<String, List<TkUserAnswerExamRecord>> m : examInit.entrySet()) {
                Map<String , Object> result = new HashMap<>(100);
                String userName = m.getKey();
                List<TkUserAnswerExamRecord> userExamInit = m.getValue();
                result.put("userName", userName);
                userExamInit.forEach(item -> {
                    BigDecimal resultScore =  ValidUtil.isEmptyAndNull(item.getFirstExactRate()) ? item.getFirstAnswerScore() : item.getFirstExactRate();

                    result.put(item.getExamId() , ValidUtil.isEmptyAndNull(resultScore) ? "无" : resultScore);

                });
                resultArr.add(result);
            }
        }

        Workbook workbook = exportExam(tkExamProductArr,resultArr);
        EasyPoiFileUtil.downLoadExcel(fileName, response, workbook);
        return "导出选中的学生答题成绩成功";
    }

    /**
     * 试题导出Excel内容组装
     * @param tkUserAnswerExamRecord
     * @return
     */
    public Workbook exportExam(List<TkExamProductMaster> tkExamProductArr,
                               List<Map<String , Object>> tkUserAnswerExamRecord) throws Exception {
        //excel标题
        List<ExcelExportEntity> entityList = new ArrayList<>();
        //内容（数据）拼接
        entityList.add(new ExcelExportEntity("学生姓名", "userName"));
        tkExamProductArr.forEach(item ->{
            entityList.add(new ExcelExportEntity(item.getExamName(), item.getExamId(),20));

        });
        // entityList.add(new ExcelExportEntity("试题单元", "appCode"));

        ExportParams params = new ExportParams(DateUtils.toShortStringFormat(new Date()) +"\u00A0"+"学生答题记录", "学生答题记录", ExcelType.XSSF);
        //设置导出样式
        params.setStyle(ExcelStyleUtil.class);

        return ExcelExportUtil.exportExcel(params, entityList, tkUserAnswerExamRecord);
    }
}